package server

import (
	"fmt"
	"net/http"
)

type ApiError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

func (e *ApiError) Error() string {
	return fmt.Sprintf("code: %d, message: %s", e.Code, e.Message)
}

// NewError 创建错误
func NewError(code int, message string) *ApiError {
	return &ApiError{
		Code:    code,
		Message: message,
	}
}

// NewMessageError 创建消息错误
func NewMessageError(format string, args ...any) *ApiError {
	return NewError(http.StatusBadRequest, fmt.Sprintf(format, args...))
}

// NewErrorWithCause 创建带有原因的错误
func NewErrorWithCause(code int, message string, cause error) *ApiError {
	return &ApiError{
		Code:    code,
		Message: fmt.Sprintf("%s: %v", message, cause),
	}
}

// 预定义错误
var (
	UnknownError        = NewError(http.StatusInternalServerError, "Unknown Error")
	UnauthorizedError   = NewError(http.StatusUnauthorized, "Unauthorized")
	ForbiddenError      = NewError(http.StatusForbidden, "Forbidden")
	NotFoundError       = NewError(http.StatusNotFound, "Not Found")
	InternalServerError = NewError(http.StatusInternalServerError, "Internal Server Error")
	BadRequestError     = NewError(http.StatusBadRequest, "Bad Request")
)
